import datetime
import json
import os
import random

from dashscope import Generation
from django.http import StreamingHttpResponse
from doctor.models import Doctor, History1, History2, History3
from user.models import User

messages = []

datas = ""

def initDoctor(name, department, user_id, doctor_id):
    global messages
    # 判断选择哪个历史表
    if user_id % 3 == 0:
        data = History1.objects.filter(user_id=user_id, doctor_id=doctor_id)
    elif user_id % 3 == 1:
        data = History2.objects.filter(user_id=user_id, doctor_id=doctor_id)
    else:
        data = History3.objects.filter(user_id=user_id, doctor_id=doctor_id)

    # 查看历史记录是否存在
    if data.exists():
        messages = json.loads(data.first().content)
    else:
        messages.clear()
        messages.append(
            {
                'role': 'system',
                'content': f'你的名字是{name}，你是一名{department}医生'
            }
        )
        content = json.dumps(messages)
        doctor = Doctor.objects.filter(id=doctor_id).first()
        user = User.objects.filter(id=user_id).first()

        # 处理history分表中数据的id为唯一值
        time_now = datetime.datetime.now()
        formatted_now = time_now.strftime("%Y%m%d%H%M%S")
        random_num = ""
        for i in range(10):
            random_num += str(random.randint(0, 9))
        if hash(user_id) % 3 == 0:
            history_id = formatted_now + "01" + random_num
            History1.objects.create(id=history_id, doctor=doctor, user=user, content=content)
        elif hash(user_id) % 3 == 1:
            history_id = formatted_now + "02" + random_num
            History2.objects.create(id=history_id, doctor=doctor, user=user, content=content)
        else:
            history_id = formatted_now + "03" + random_num
            History3.objects.create(id=history_id, doctor=doctor, user=user, content=content)
    return messages

def get_see(response, user_id, doctor_id):
    global datas
    datas = ""
    for res in response:
        if res.status_code == 200:
            data = res.output.choices[0].message.content
            datas += data
            print(datas)
            data1 = f"data:{data}\n\n"
            if data:
                yield data1.encode("utf-8")
            else:
                messages.append({"role": "system", "content": datas})
                print(datas)
                user = User.objects.filter(id=user_id).first()
                doctor = Doctor.objects.filter(id=doctor_id).first()
                if hash(int(user_id)) % 3 == 0:
                    obj = History1.objects.get(user=user, doctor=doctor)
                elif hash(int(user_id)) % 3 == 1:
                    obj = History2.objects.get(user=user, doctor=doctor)
                else:
                    obj = History3.objects.get(user=user, doctor=doctor)
                print(messages)
                obj.content = json.dumps(messages)
                obj.save()
                return "no message".encode("utf-8")

# def ai_doctor(messages):
#     response = Generation.call(
#         api_key=os.getenv("DASHSCOPE_API_KEY"),
#         model='qwen-plus',
#         messages=messages,
#         result_format="message"
#     )
#     return response

# def get_message(message):
#     messages.append({'role': 'user', 'content': message})
#     assistant_output = ai_doctor(messages).output.choices[0].message.content
#     messages.append({'role': 'system', 'content': assistant_output})
#     print(f"模型输出：{assistant_output}")
#     print("\n")
#     return assistant_output

def get_message(message, user_id, doctor_id):
    messages.append({'role': 'user', 'content': message})
    response = Generation.call(
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        model='qwen-plus',
        messages=messages,
        result_format="message",
        stream=True,
        incremental_output=True,
    )
    response = StreamingHttpResponse(get_see(response, user_id, doctor_id), content_type='text/event-stream')
    response['Cache-Control'] = 'no-cache'
    return response
